package org.jfk.core.model;

import org.apache.log4j.Logger;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.Table;
import com.jfinal.plugin.activerecord.TableMapping;

public class HttpRequestBlackList extends BaseModel<HttpRequestBlackList>{

	private static Logger logger = Logger.getLogger(HttpRequestBlackList.class);	
	public static final HttpRequestBlackList dao;
	public static final Table table;
	public static final String tableName;

	static {
		dao = new HttpRequestBlackList();
		table = TableMapping.me().getTable(HttpRequestBlackList.class);
		tableName = table.getName();
	}
	
	/**
	 * 判别是否允许访问
	 * @param ip
	 * @param url
	 * @return
	 */
	public boolean isAllow(String ip,String url){
		
		
		Record record = Db.findFirst("select * from " + tableName + " where remote_ip = ? and req_url = ?", ip,url);
		if (record != null && record.getInt("is_allow").intValue() == 3201){
			return false;
		}

		record = Db.findFirst("select * from " + tableName + " where remote_ip = ? and req_url = ?", ip,"all");
		if (record != null && record.getInt("is_allow").intValue() == 3201){
			return false;
		}

		record = Db.findFirst("select * from " + tableName + " where remote_ip = ? and req_url = ?", "all",url);
		if (record != null && record.getInt("is_allow").intValue() == 100102){
			return false;
		}
		
		return true;
	}


	/**
	 * 保存新的高频请求
	 */
	@Override
	public boolean save() {
		synchronized(tableName){
			String ip = this.getStr("REMOTE_IP");
			String url = this.getStr("REQ_URL");
			HttpRequestBlackList record = HttpRequestBlackList.dao.findFirst("select * from " + tableName + " where remote_ip = ? and req_url = ? ", ip,url);
			if (record == null){
				return super.save();
			}else{
				//record.update();
				return false;
			}
		}
	}
	
}
